package com.ruoyi.system.listenetr;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.service.IUserService;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

public class UserListener implements ReadListener<SysUser> {
    public static final int BACH_COUNT=3;
    private List<SysUser> cacheDataList = ListUtils.newArrayListWithExpectedSize(BACH_COUNT);
    private IUserService userService;

    public UserListener(IUserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(SysUser sysUser, AnalysisContext analysisContext) {
        System.out.println("解析的数据"+sysUser);
        cacheDataList.add(sysUser);
        if(cacheDataList.size()>=BACH_COUNT){
            //保存到数据库
            System.out.println("list"+cacheDataList);
            userService.addBath(cacheDataList);
            cacheDataList = ListUtils.newArrayListWithExpectedSize(BACH_COUNT);
        }
    }
    @RequestMapping("exportData")
    public void exportData() {
        // 每个 sheet 写入的数据
        int NUM_PER_SHEET = 10000;
        String fileName = "BigData.xlsx";
        // 获取数据
        List<SysUser> list = userService.list(null);
        // 获取 sheet 的个数
        int sheetNum = list.size() % NUM_PER_SHEET == 0 ? list.size() / NUM_PER_SHEET : list.size() / NUM_PER_SHEET + 1;
        // 指定写入的文件
        ExcelWriter excelWriter = EasyExcel.write(fileName, SysUser.class).build();
        for (int i = 0; i < sheetNum; i++) {
            // 设置 sheet 的名字（sheet不能相同）
            String sheetName = "sheet" + i;
            System.out.println(sheetName);
            // 生成Sheet
            WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetName).build();
            int startNum = i * NUM_PER_SHEET;
            int endNum = i == sheetNum - 1 ? list.size() : (i + 1) * NUM_PER_SHEET;
            excelWriter.write(list.subList(startNum, endNum), writeSheet);
        }
        System.out.println("999");
        // 最好放在 finally中
        excelWriter.finish();
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完成");
        if(cacheDataList.size()>=1){
            System.out.println("list"+cacheDataList);
            userService.addBath(cacheDataList);
        }
    }
}
